<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 红包管理
 * Class Promotion
 * @author heyu
 */
class Promotion extends MY_Controller {

    /**
     * @var ConsumerPromotionModel
     */
    public $mPromotion = null;

	public function __construct(){
		parent::__construct();
        $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');
	}
	
	/**
	 * 首页
	 */
	public function index(){
//        $requestData = [
//            "OrderCode"=>"887375290751390336",
//            "ShipperCode"=>'YTO',
//            "LogisticCode"=>'887515411587128641'
//        ];
//        $kd = KDNiao()->getOrderTracesByJson($requestData);  // 查看物流信息
//        p($kd);
        $data = array(
            'status' => $this->mPromotion->getStatus(),
            'type' => $this->mPromotion->BONUS_TYPE,
            'title' => '红包管理'
        );
		$this->view('config/promotion/home', $data, 'datatable,datepicker');
	}
	
    /**
     * 获取列表数据
     */
    public function getList(){
        $data = $this->mPromotion->adminPcGetBonusList();
        $type = $this->mPromotion->BONUS_TYPE;
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['name'];
            $data['aaData'][$k][] = isset($type[$v['type']]) ? $type[$v['type']] : '';
            $data['aaData'][$k][] = $v['money'];
            $data['aaData'][$k][] = $v['condition'];
            $data['aaData'][$k][] = $v['send_number'];
            $data['aaData'][$k][] = $v['surplus_number'];
            $data['aaData'][$k][] = isset($v['use_end_time']) ? dateFormat($v['use_end_time']) : '';
            $data['aaData'][$k][] = dateFormat($v['addtime']);
            if ($v['status'] == 1 && $v['use_end_time'] <= time()){
                $v['status'] = 3;
            }
            $data['aaData'][$k][] = $this->mPromotion->getStatus($v['status'], true);
            $btnConfig = '';
            if ($v['status'] == 2){
                $btnConfig = adminCreateBtn(array(
                    'label' => ' 详情',
                    'attr' => array(
                        'href' => getUrl('config/promotion/details').'?id='.$v['id'],
                        'class' => 'btn btn-xs green-stripe default',
                    ),
                    'tag' => 'a'
                ));
            }else if ($v['status'] == 3){
                $btnConfig = adminCreateBtn(array(
                    'label' => ' 发布',
                    'attr' => array(
                        'href' => getUrl('config/promotion/changeStatus').'?id='.$v['id'],
                        'class' => 'btn btn-xs yellow-stripe default ajax-request-btn',
                        'alert-message' => '是否确认发布 “ '.$v['name'].' ” ？'
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'config',
                        'key' => 'promotion-status'
                    )
                ));
                $btnConfig .=' '. adminCreateBtn(array(
                    'label' => ' 编辑',
                    'attr' => array(
                        'href' => getUrl('config/promotion/edit').'?id='.$v['id'],
                        'class' => 'btn btn-xs blue-stripe default',
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'config',
                        'key' => 'promotion-edit'
                    )
                ));
            }
            $btnConfig .= ' '.adminCreateBtn(array(
                    'label' => ' 删除',
                    'attr' => array(
                        'href' => getUrl('config/promotion/deleteBonus').'?id='.$v['id'],
                        'alert-message' => "确认是否删除“ ".$v['name']." ”？",
                        'class' => 'ajax-request-btn btn btn-xs red-stripe default',
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'config',
                        'key' => 'promotion-delete'
                    )
                ));
            $data['aaData'][$k][] = $btnConfig;
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 增加/发放红包
     */
    public function add(){
        $data = array(
            'title'=>'添加',
            'add'=>1,
            'type' => $this->mPromotion->BONUS_TYPE
        );

        $this->view('config/promotion/form', $data, 'datatable,validation,uniform,datepicker');
    }

    /**
     * 编辑
     */
    public function edit(){
        $tA = $this->mPromotion->getInfo(get('id'));
        if ( ! $tA){
            show_404();
        }
        $data = array(
            'title'=>'编辑',
            'add'=>0,
            'type' => $this->mPromotion->BONUS_TYPE,
            'info' => $tA
        );
        $this->view('config/promotion/form', $data, 'datatable,validation,uniform,datepicker');
    }

    /**
     * 保存数据
     */
    public function save(){
        //表单验证
        $vConf = array(
            array('name', '名称', 'required'),
            array('money', '面额', 'required'),
            array('condition', '消费金额', 'required'),
            array('use_start_time', '使用起始日期', 'required'),
            array('use_end_time', '使用截止日期', 'required'),
            array('type', '发放类型', 'required|in_list[1,2,3,4]'),
        );
        $type = (int)post('type');
        if ($type == 3 || $type == 1){
            $vConf[] = array('send_number', '发放总数量', 'required|is_natural_no_zero');
            $vConf[] = array('send_start_time', '发放开始日期', 'required');
            $vConf[] = array('send_end_time', '发放结束日期', 'required');
        }
        $this->formDataValidation($vConf);

        $id = intval(post('id'));
        $consumerIds = post('consumer_ids');
        $sendNumber = post('send_number');
        $money = post('money');
        $condition = post('condition');
        $sendStartTime = trim(post('send_start_time'));
        $sendEndTime = trim(post('send_end_time'));
        $useStartTime = trim(post('use_start_time'));
        $useEndTime = trim(post('use_end_time'));
        if ($money <= 0){
            $this->ajaxReturn(0, '请选择正确的面额金额');
        }
        if ($money >= 100){
            $this->ajaxReturn(0, '请发放面额小于100的红包');
        }
        if ($condition <= 0){
            $this->ajaxReturn(0, '请选择正确的消费金额');
        }
        if ($consumerIds){
            $consumerId = explode(',', $consumerIds);
            $sendNumber = count($consumerId);

        }

        if ($type == 2){
            if (empty($consumerIds)){
                $this->ajaxReturn(0, '请选择用户');
            }
            if ($id > 0){
                $this->ajaxReturn(0, '按用户发放不可编辑');
            }
        }else{
            $sendStartTime = strtotime($sendStartTime);
            $sendEndTime = strtotime($sendEndTime);
            if (!$sendStartTime) {
                $this->ajaxReturn(0, '请选择正确的发放开始日期');
            }
            if (!$sendEndTime) {
                $this->ajaxReturn(0, '请选择正确的发放结束日期');
            }
            if ($sendStartTime > $sendEndTime){
                $this->ajaxReturn(0, '发放开始日期不得大于结束时间');
            }
        }
        $useStartTime = strtotime($useStartTime);
        $useEndTime = strtotime($useEndTime);
        if (!$useStartTime) {
            $this->ajaxReturn(0, '请选择正确的使用起始日期');
        }
        if ( !$useEndTime) {
            $this->ajaxReturn(0, '请选择正确的使用截止日期');
        }
        if ($useStartTime > $useEndTime){
            $this->ajaxReturn(0, '使用起始日期不得大于截止日期');
        }
        $time = time();
        $money = floor( $money* 10 ) /10;
        $money = sprintf('%.1f', (float)$money);
        $data = array(
            'name' => trim(post('name')),
            'money' => $money,
            'condition' => $condition,
            'type' => $type,
            'send_number' => $sendNumber,
            'surplus_number' => $sendNumber,
            'send_start_time' => $type == 2 ? null:$sendStartTime,
            'send_end_time' => $type == 2 ? null:$sendEndTime+86399,
            'use_start_time' => $useStartTime,
            'use_end_time' => $useEndTime+86399,
            'status' => $type == 3 ? 3 : 2,
        );
        $this->db->trans_begin();
        if (!$id){
            $data['addtime'] = $time;
        }
        $bonusId = $this->mPromotion->save($data, $id);
        if (!$bonusId){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        if ($type == 2){
            $lData = array();
            foreach ($consumerId as $k => $v){
                if (isset($v) && $v > 0) {
                    $lData[] = array(
                        'bonus_id' => $bonusId,
                        'type' => $type,
                        'consumer_id' => $v,
                        'money' => $money,
                        'status' => 1,
                        'addtime' => $time
                    );
                }
            }
            $tA = $this->mPromotion->saveBonusLog($lData, 0, true);
            if (!$tA){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
        }
        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功', NULL, getUrl('config/promotion'));
    }

    /**
     * 详情
     */
    public function details(){
        $info = $this->mPromotion->getInfo(get('id'));
        if ( ! $info){
            show_404();
        }
        $data = array(
            'info' => $info,
            'status'=>$this->mPromotion->getBonusLogStatus(false),
            'title'=>'详情',
        );

        $this->view('config/promotion/details', $data, 'datatable,validation,uniform,datepicker');
    }

    /**
     * 获取按用户发放红包详情
     */
    public function getBonusLog(){
        $data = $this->mPromotion->adminPcGetBonusLogList();
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = isset($v['consumer']) ? $v['consumer'] : $v['consumer_mobile'];
            $data['aaData'][$k][] = $v['money'];
            $data['aaData'][$k][] = $v['order_code'];
            $data['aaData'][$k][] = $v['code'];
            $data['aaData'][$k][] = $this->mPromotion->getBonusLogStatus($v['status'], true);
            $data['aaData'][$k][] = isset($v['usedtime']) ? dateFormat($v['usedtime']) : '';
            $data['aaData'][$k][] = dateFormat($v['addtime']);
            $data['aaData'][$k][] = $this->mPromotion->getStatus($v['status'], true);
            $data['aaData'][$k][] = '';
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 修改状态
     */
    public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));

        $id = (int)get('id');
        $info = $this->mPromotion->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '红包不存在');
        }
        if ($info['type'] == 3 && $info['status'] == 3){
            $tA = $this->mPromotion->save(array('status' => 2), $id);
            if (!$tA){
                $this->ajaxReturn(0, '保存失败');
            }
        }
        $this->ajaxReturn(1, '保存成功');
    }

    /**
     * 删除
     */
    public function deleteBonus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));

        $id = (int)get('id');
        $info = $this->mPromotion->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '红包不存在或已删除');
        }
        if ($info['status'] == 1){
            $this->ajaxReturn(0, '红包已删除');
        }
        if ($info['status'] == 3){
            $tA = $this->mPromotion->deleteBonus($id);
            if (!$tA){
                $this->ajaxReturn(0, '删除失败');
            }
        }else if ($info['status'] == 2){
            $tA = $this->mPromotion->save(array('status' => 1), $id);
            if (!$tA){
                $this->ajaxReturn(0, '删除失败');
            }
        }else{
            $this->ajaxReturn(0, '数据错误');
        }
        $this->ajaxReturn(1, '删除成功');
    }

    /**
     * 获取用户列表
     */
    public function getConsumerList(){
        $this->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
        $data = $this->mConsumer->adminGetList();
        foreach ($data['data'] as $k => $v){
            $img = isset($v['portrait']) ? getImage($v['portrait'], 'xs') : getDefaultPortrait();
            $data['aaData'][$k][] = '<input type="checkbox" class="checkboxes" name="consumer_id[]" value="' . $v['id'] .'">';
            $data['aaData'][$k][] = '<img src="'.$img.'" class="portrait img-wh"/>';
            $data['aaData'][$k][] = $v['realname'];
            $data['aaData'][$k][] = $v['nickname'];
            $data['aaData'][$k][] = $v['mobile'];
            $data['aaData'][$k][] = isset($v['last_login_time']) ? dateFormat($v['last_login_time']) : '';
            $data['aaData'][$k][] = $this->adminStatus($v['status'], true);
            $data['aaData'][$k][] = '';
        }
        unset($data['data']);
        echo json_encode($data);
    }
}
